﻿using System.Windows.Media;
using System.Windows.Media.Imaging;
using ImageProcessor.Shared;
using ImageProcessor.Shared.ImageExtensions;

namespace ImageProcessor.Tim
{
    public class BinarizationVM : ImageProcessorBaseVM
    {
        private ImageSource _resultImage;
        private double _threshold;

        public BinarizationVM(MainViewModel mainVM) : base(mainVM)
        {
            Threshold = 0.5;
        }

        public ImageSource ResultImage
        {
            get { return _resultImage; }
            private set
            {
                if (_resultImage == value)
                    return;
                _resultImage = value;
                OnPropertyChanged("ResultImage");
            }
        }

        public double Threshold
        {
            get { return _threshold; }
            set
            {
                if(_threshold == value)
                    return;
                _threshold = value;
                OnPropertyChanged("Threshold");
            }
        }

        protected override void Execute(object obj)
        {
            var bitmap = ((BitmapSource) MainVM.SourceImage).BitmapSourceToBitmap();

            for (int y = 0; y < bitmap.Height; ++y)
            {
                for (int x = 0; x < bitmap.Width; ++x)
                {
                    var pixel = bitmap.GetPixel(x, y);
                    if (pixel.GetBrightness() < Threshold)
                        bitmap.SetPixel(x,y,System.Drawing.Color.Black);
                    else
                        bitmap.SetPixel(x, y, System.Drawing.Color.White);
                }
            }

            ResultImage = bitmap.BitmapToBitmapSource();
        }

        protected override bool CanExecute(object obj)
        {
            return MainVM.SourceImage != null;
        }
    }
}